<?php

namespace zhtfrontend\models\datas;

use common\components\behaviors\UpdateCacheBehavior;
use common\components\extenders\MenuManage;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\components\helpers\Util;
use common\models\datas\Brand;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use common\models\datas\Type;
use doumiaoduo\ueditor\ImageUploadMultipleTrait2;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use zhtfrontend\components\services\goods\ReportAction;

/**
 * This is the model class for table "{{%goods}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $sn
 * @property integer $cat_id
 * @property integer $type_id
 * @property integer $brand_id
 * @property string $price
 * @property string $cost
 * @property string $market_price
 * @property integer $store
 * @property string $picture
 * @property string $description
 * @property string $content
 * @property integer $is_shelve
 * @property integer $is_delete
 * @property integer $is_buy
 * @property integer $site_id
 * @property integer $mechanic_id
 * @property string $nostore_sell
 * @property integer $max_buy
 * @property integer $comment_count
 * @property integer $browse_count
 * @property integer $buy_count
 * @property integer $score
 * @property string $goods_type
 * @property integer $store_prompt
 * @property integer $is_show
 * @property integer $up_at
 * @property integer $down_at
 * @property integer $updated_at
 * @property integer $created_at
 * @property integer $admin_id
 * @property integer $course_attr_id
 */
class Goods extends \zhtfrontend\components\bases\BaseModel
{
    use ImageUploadMultipleTrait2;
    public $suitable_age;
    public $min_age;
    public $max_age;
    public $region;
    public $groupIds; //添加组合商品
    public $group_price; //组合完价格
    public $class_count;
    public $teacher_id;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%goods}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat_id', 'type_id', 'brand_id', 'store', 'is_shelve', 'is_delete', 'is_buy', 'site_id', 'mechanic_id', 'max_buy',
                'comment_count', 'browse_count', 'buy_count', 'score', 'store_prompt', 'is_show', 'up_at', 'down_at', 'updated_at',
                'created_at', 'distribution_way','arrangement_id','min_age','max_age','is_booking','teaching_methods','is_group','category_id','tutor_id','subsidy_type','class_count','commission_rate','teacher_id','status','class_hour','menu_id','is_update_price'], 'integer'],
            [['price', 'cost', 'market_price','distribution_proportion','deposit','admission_fee','deposit','admission_fee','group_price'], 'number'],
            [['description', 'content','groupIds','auditing'], 'string'],
            [['name'], 'string', 'max' => 255],
            [['sn','region'], 'string', 'max' => 100],
            [['picture'], 'string', 'max' => 255],
            [['nostore_sell'], 'string', 'max' => 10],
            [['goods_type'], 'string', 'max' => 20],
            [['nostore_sell'],'default','value'=>'N'],
            [['is_buy','is_shelve'],'default','value'=>0],
            [['is_show'],'default','value'=>1],
            [['is_classroom'],'default','value'=>1],
            [['name','cat_id','brand_id','price','cost','market_price','store','max_buy','store_prompt'],'required'],
            [['mechanic_id'],'check_Mechanic','on'=>['create','update']],

            [['store','market_price','cost','price','max_buy','score','store_prompt'], 'compare', 'compareValue' => 0, 'operator' => '>='],
            [['store','market_price','cost','price','max_buy','score','store_prompt'], 'compare', 'compareValue' => 100000, 'operator' => '<='],
            [['cat_id'],'category_check'],
            [['cost','deposit','admission_fee'],'required','on'=>['set']],
            [['deposit'],'chack_fee','on'=>['setdeposit']],
            [['subsidy_type'],'required','on'=>['set']],
            [['max_age'],'check_suitable_age','on'=>['update']],
            [['min_age','max_age','region'],'required','when'=>function($model){
                 return $model->type_id == 1;
            },'on'=>['update']],
            [['auditing'],'required','when'=>function($model){
                return $model->status == 2;
            },'on'=>['auditing']],
            [['groupIds'],'validate_group','skipOnEmpty'=>false,'on'=>['addskill']],
            [['group_price'],'validate_group_price','skipOnEmpty'=>false,'on'=>['addskill']],
//            [['auditing'],'required','on'=>['auditing']],
        ];

    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        if($this->type_id == 1)
            $cost = '课时补贴';
        else
            $cost = '成本价';
        return [
            'id' => Yii::t('zhtfrontend', '自增编号'),
            'name' => Yii::t('zhtfrontend', '商品名称'),
            'sn' => Yii::t('zhtfrontend', '商品编号'),
            'cat_id' => Yii::t('zhtfrontend', '分类'),
            'type_id' => Yii::t('zhtfrontend', '类型'),
            'brand_id' => Yii::t('zhtfrontend', '品牌'),
            'price' => Yii::t('zhtfrontend', '销售价'),
            'cost' => Yii::t('zhtfrontend', $cost),
            'market_price' => Yii::t('zhtfrontend', '市场价'),
            'store' => Yii::t('zhtfrontend', '库存'),
            'picture' => Yii::t('zhtfrontend', '商品图片'),
            'description' => Yii::t('zhtfrontend', '描述'),
            'content' => Yii::t('zhtfrontend', '商品详情'),
            'is_shelve' => Yii::t('zhtfrontend', '上下架'),
            'is_delete' => Yii::t('zhtfrontend', '是否删除'),
            'is_buy' => Yii::t('zhtfrontend', '是否可购买'),
            'site_id' => Yii::t('zhtfrontend', '广场id'),
            'mechanic_id' => Yii::t('zhtfrontend', '机构'),
            'nostore_sell' => Yii::t('zhtfrontend', '无库存是否可购买'),
            'max_buy' => Yii::t('zhtfrontend', '最大购买量'),
            'comment_count' => Yii::t('zhtfrontend', '评论数'),
            'browse_count' => Yii::t('zhtfrontend', '浏览数量'),
            'buy_count' => Yii::t('zhtfrontend', '购买量'),
            'score' => Yii::t('zhtfrontend', '赠送积分'),
            'goods_type' => Yii::t('zhtfrontend', '商品类型'),
            'store_prompt' => Yii::t('zhtfrontend', '库存警告'),
            'is_show' => Yii::t('zhtfrontend', '是否显示'),
            'up_at' => Yii::t('zhtfrontend', '上架时间'),
            'down_at' => Yii::t('zhtfrontend', '下架时间'),
            'updated_at' => Yii::t('zhtfrontend', '修改时间'),
            'created_at' => Yii::t('zhtfrontend', '添加时间'),
            'admin_id' => Yii::t('zhtfrontend', '添加人'),
            'arrangement_id' => Yii::t('zhtfrontend', '排课id'),
            'distribution_way' => Yii::t('zhtfrontend', '分成方式'),
            'distribution_proportion' => Yii::t('zhtfrontend', '分成比例'),
            'deposit' => Yii::t('zhtfrontend', '保证金'),
            'admission_fee' => Yii::t('zhtfrontend', '招生费用'),
            'max_age' => Yii::t('zhtfrontend', '最大年龄'),
            'min_age' => Yii::t('zhtfrontend', '最小年龄'),
            'suitable_age' => Yii::t('zhtfrontend', '适合年龄段'),
            'region' => Yii::t('zhtfrontend', '区域'),
            'groupIds' => Yii::t('zhtfrontend', '艺教学组id'),
            'is_booking' => Yii::t('zhtfrontend', '是否可预约'),
            'is_group' => Yii::t('zhtfrontend','是否是组合'),
            'teaching_methods' => Yii::t('zhtfrontend','课程方式'),
            'category_id' => Yii::t('zhtfrontend','三大类'),
            'tutor_id' => Yii::t('zhtfrontend','导师id'),
            'group_price' => Yii::t('zhtfrontend','组合完价格'),
            'subsidy_type' => Yii::t('zhtfrontend','课时补贴类型'),
            'class_count' => Yii::t('zhtfrontend','课次'),
            'commission_rate' => Yii::t('zhtfrontend','佣金比例'),
            'teacher_id' => Yii::t('zhtfrontend','老师'),
            'is_classroom' => Yii::t('zhtfrontend','是否有教室'),
            'class_hour' => Yii::t('zhtfrontend','课时数'),
            'status' => Yii::t('zhtfrontend','审核状态'),
            'auditing' => Yii::t('zhtfrontend','审核意见'),
            'menu_id' => Yii::t('zhtfrontend','绑定模块'),
            'is_update_price' => Yii::t('zhtfrontend','是否修改价格'),
        ];
    }
    public function fields()
    {
        $fields = parent::fields();
        $fields['shelve_status'] = function () {
            return $this->is_shelve;
        };
        $fields['is_shelve'] = function () {
            switch ($this->is_shelve) {
                case 0:
                    if(isset(\Yii::$app->user->identity->role) && in_array(\Yii::$app->user->identity->role,['mechanic','class_teacher','teache_teacher','reception','finance'])){
                        return \Yii::t('zhtfrontend', "<span style='color:#ff659a'>下架</span>");
                    }else {
                        return \Yii::t('zhtfrontend', "<span style='color:#ff659a;cursor: pointer' title='点击上架' class='shelve' data-id='".$this->id."'>下架</span>");
                    }

                case 1:
                    if( isset(\Yii::$app->user->identity->role) && in_array(\Yii::$app->user->identity->role,['mechanic','class_teacher','teache_teacher','reception','finance'])){
                        return \Yii::t('zhtfrontend', "<span style='color:#0E4DAA'>已上架</span>");
                    }else {
                        return \Yii::t('zhtfrontend', "<span style='color:#0E4DAA;cursor: pointer' title='点击下架' class='shelve' data-id='".$this->id."'>已上架</span>");
                    }

            }
        };
        $fields['is_delete'] = function () {
            switch ($this->is_delete) {
                case 0:
                    return \Yii::t('zhtfrontend', '删除');
                case 1:
                    return \Yii::t('zhtfrontend', '正常');
            }
        };
        $fields['is_buy'] = function () {
            switch ($this->is_buy) {
                case 0:
                    return \Yii::t('zhtfrontend', '不可购买');
                case 1:
                    return \Yii::t('zhtfrontend', '可购买');
            }
        };
        $fields['is_show'] = function () {
            switch ($this->is_show) {
                case 0:
                    return \Yii::t('zhtfrontend', '隐藏');
                case 1:
                    return \Yii::t('zhtfrontend', '显示');
            }
        };
        $fields['created_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->created_at);
        };
        $fields['updated_at'] = function () {
            return \Yii::$app->formatter->asDatetime($this->updated_at);
        };

        $fields['status'] = function () {
            switch ($this->status) {
                case 0:
                    return \Yii::t('zhtfrontend', '未设置');
                case 1:
                    return \Yii::t('zhtfrontend', '上架');
                case 2:
                    return \Yii::t('zhtfrontend', '驳回');
                case 3:
                    return \Yii::t('zhtfrontend', '待审核');
            }
        };

        return $fields;
    }


    public function extraFields()
    {
        return [
            'shelve_status' => function () {
                switch ($this->is_shelve) {
                    case 0:
                        return "<span style='color:#ff659a'>下架</span>";
                    case 1:
                        return "<span style='color:#0E4DAA'>上架</span>";
                }
            },
            'type_name' => function (){
                switch ($this->type_id){
                    case 1:
                        return \Yii::t('zhtfrontend','课程商品');
                    case 2:
                        return \Yii::t('zhtfrontend','乐器商品');
                    case 5:
                        return \Yii::t('zhtfrontend','组合商品');

                }
            },
            'admin' => function () {
                return isset($this->admin) ? $this->admin->username : '';
            },
            'class_time'=>function(){
                $str = '';
                if(isset($this->goodsClassTime)){
                    foreach($this->goodsClassTime as $time){
                        $str .= Util::getWeek($time->class_day).$time->start_time.'-'.$time->end_time.' ';
                    }
                }
                return $str;
            },
            'cate_name' => function () {
                \Yii::$app->cacheManage->cacheName='Cate';
                $cate_cache=\Yii::$app->cacheManage->findCache();
                if(!empty($cate_cache)){//缓存中存在了cache
                    if(isset($cate_cache[$this->cat_id]) && $cate_cache[$this->cat_id]!=null){
                        return $cate_cache[$this->cat_id]['name'];
                    }
                }
                return isset($this->cate) ? $this->cate->name : '';
            },
            'mechanic_name' => function () {
                return isset($this->mechanic) ? $this->mechanic->name : '';
            },
            'room_name'=>function(){
               $room =  GoodsAttr::find()->where(['goods_id'=>$this->id,'obj_type'=>'classroom_name'])->one();
               return isset($room->value)?$room->value:'';
            },

            'teacherStr'=>function(){
                $str = '';
                if(!empty($this->goodsteacher)){
                    foreach ($this->goodsteacher as $t){
                        $str .= $t->teacher_name;
                    }
                }
                return $str;
            },
            'checkbox'=>function(){
                return Html::checkbox('goodsId',false,['value'=>$this->id]);
            },
            'brand_name' => function () {
                \Yii::$app->cacheManage->cacheName='Brand';
                $brand_cache=\Yii::$app->cacheManage->findCache();
                if(!empty($brand_cache) && isset($brand_cache[$this->brand_id]) && $brand_cache[$this->brand_id] != null){
                    return $brand_cache[$this->brand_id]['name'];
                }
                return isset($this->brand) ? $this->brand->name : '';
            },
            'status_name'=>function(){
                $result = ReportRecord::find()->where(['type'=>1,'module_id'=>$this->id])->orderBy('id DESC')->limit(1)->one();
                if($result != null){
                    if($result->stage == 1){
                        return '已提报审核';
                    }
                    if($result->stage == 2){
                       if($result->status == 1){
                           return '机构负责人已通过';
                       }else{
                           return '机构负责人未通过';
                       }
                    }if($result->stage == 3){
                        if($result->status == 1){
                            return '教务已通过';
                        }else{
                            return '教务未通过';
                        }
                    }if($result->stage == 4){
                        if($result->status == 1){
                            return '上架';
                        }else{
                            return '财务未通过';
                        }
                    }

                }else{
                    return '未提报';
                }
            },
            'operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'delete' => function ($data) {
                            $state = ClassManage::find()->where(['associate_id' => $data['id'],'is_old'=>0])->one();
                            if (!empty($state)) {
                                return '<button class="yx-btn-disabled" type="button">删除</button>';
                            } else {
                                return '';
                            }
                        },
                        'setlist' => function ($data) {
                            return '';
                        },
                        'setdeposit' => function ($data) {
                            if($data['status'] != 3){
                                return '<button class="yx-btn-disabled" type="button">设置保证金</button>';
                            }else{
                                return '';
                            }
                        },
                        'details'=> function(){
                            return '';
                        },
                        'update'=> function($data){

                           // $state = ClassManage::find()->where(['associate_id' => $data['id'],'is_old'=>0])->one();
                            if ($data['status'] == 1) {
                                return '<button class="yx-btn-disabled" type="button">修改</button>';
                            } else {
                                return '';
                            }
                        },
                        'add'=> function($data){
                            $state = ClassManage::find()->where(['associate_id' => $data['id'],'is_old'=>0])->one();
                            if (!empty($state)) {
                                return '<button class="yx-btn-disabled" type="button">增加艺术教学</button>';
                            } else {
                                return '';
                            }
                        },
//                        'audit'=> function($data){
//                            if($data['is_shelve'] != 2){
//                                return '<button style="color:#fff;border: none;padding: 1px 12px;border-radius:2px" type="button">审核</button>';
//                            }else{
//                                return '';
//                            }
//                        },
                        'report'=> function($data){
                            return '';
                        },
                        'auditing'=> function($data){
                            if($data['status'] != 3){
                                return '<button class="yx-btn-disabled" type="button">审核</button>';
                            }else{
                                return '';
                            }
                        }
                    ]
                )->create();
            },
            'pro_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'update' => function ($data) {
                            return '';
                        },
                    ]
                )->create();
            },
            'mechanicoperate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'report' => function ($data) {//机构代表提报按钮
                            $price = GoodsPrice::find()->where(['goods_id'=>$this->id])->all();
                           if($this->status == 0 && $price != null){
                               return '';
                           }else{
                               return '<button class="yx-btn-disabled" type="button">提报上架</button>';
                           }

                        },
                        'audit' => function ($data) {//机构代表审核按钮
                            if($this->status == 2){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">审核上架</button>';
                            }
                        },
                    ]
                )->create();
            },
            'squareoperate' =>function(){
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->isDisable(
                    [
                        'edaudit' => function ($data) {//教务审核按钮
                            if($this->status == 3){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">教务审核</button>';
                            }
                        },
                        'report' => function ($data) {//教务提报按钮
                            if($this->status == 0){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">提报上架</button>';
                            }
                        },
                        'financeaudit' => function ($data) {//财务审核按钮
                            if($this->status == 4){
                                return '';
                            }else{
                                return '<button class="yx-btn-disabled" type="button">财务审核</button>';
                            }
                        },
                    ]
                )->create();
            },
            'discount_type' => function(){
                return "<select name = 'discount_type[".$this->id."]' style='width: 120px'>
                          <option value = '0'>请选择</option>
                          <option value = '1'>按比例(%)</option>
                          <option value = '2'>固定减额</option>
                        </select>  ";
            },
            'price_reduce' => function(){
                return "<input type = 'text' name = 'price_reduce[".$this->id."]' value=0 style='width: 50px'/>";
            },
            'cost_reduce' => function(){
                return "<input type = 'text' name = 'cost_reduce[".$this->id."]' value=0 style='width: 50px'/>";
            },
            'market_price_reduce' => function(){
                return "<input type = 'text' name = 'market_price_reduce[".$this->id."]' value=0 style='width: 50px'/>";
            },
            'class_time' =>function(){
                $time = GoodsClassTime::find()->where(['goods_id'=>$this->id])->all();
                $tt = '';
                if($time != null){
                    foreach ($time as $t){
                        $tt .= Util::getWeek($t->class_day).' '. $t->start_time.'-'.$t->end_time;
                    }
                }
                return $tt;
            },
            'class_count' => function(){
                $classCount = GoodsAttr::find()->where(['goods_id'=>$this->id,'obj_type'=>'class_count'])->one();
                $num = 0;
                if($classCount != null){
                    $num = $classCount->value;
                }
                return $num;
            }
        ];
    }

    public function getAdmin()
    {
        return $this->hasOne(Admin::className(), ['id' => 'user_id']);
    }

    public function  getMechanic()
    {
        return $this->hasOne(Mechanic::className(), ['id' => 'mechanic_id']);
    }

    public function  getCate()
    {
        return $this->hasOne(Cate::className(), ['id' => 'cat_id']);
    }
    public function  getBrand()
    {
        return $this->hasOne(Brand::className(), ['id' => 'brand_id']);
    }

    public function getType(){
        return $this->hasOne(Type::className(),['id'=>'type_id']);
    }

    public function getGoodsattr(){
        return $this->hasMany(GoodsAttr::className(),['goods_id'=>'id']);
    }

    public function getGoodsteacher(){
        return $this->hasMany(GoodsTeacher::className(),['goods_id'=>'id']);
    }

    public function getGoodsClassTime(){
        return $this->hasMany(GoodsClassTime::className(),['goods_id'=>'id']);
    }

    public function getClassmanage(){
        return $this->hasOne(ClassManage::className(),['associate_id'=>'id'])->where(['is_old'=>0]);
    }

    public function getClassmanages(){
        return $this->hasOne(ClassManage::className(),['associate_id'=>'id'])->where(['is_old'=>0,'status'=>[0,1]]);
    }

    public function getTutor(){
        return $this->hasOne(Tutor::className(),['id'=>'tutor_id']);
    }

    public function check_Mechanic($attribute){
        $mechanic = Mechanic::find()->where(['parent_id'=>$this->mechanic_id])->all();
        if($mechanic != null){
            $this->addError($attribute, Yii::t('zhtfrontend', '请选择子级机构'));
        }

    }
    public function chack_fee($attribute){
        if(($this->deposit) <= 0){
            $this->addError($attribute, Yii::t('zhtfrontend', '保证金大于零'));
        }

    }
    //验证组合商品的商品个数
    public function validate_group($attribute){
            if($this->$attribute == ''){
                $this->addError($attribute, Yii::t('zhtfrontend', '请选择艺教学组'));
            }
    }

    //验证组合价格
    public function validate_group_price($attribute){
            if($this->$attribute == '' || $this->$attribute == 0){
                $this->addError($attribute, Yii::t('zhtfrontend', '请选计算价格'));
            }
    }

    //    检测是否为二级分类
    public function category_check($attribute)
    {
        $categorys = Fun::cache('cate_cache', false);
        $tree = new Tree($categorys);
        $categoryLevel = $tree->get_level($this->$attribute);
        if ($categoryLevel == 1) {
            $this->addError($attribute, \Yii::t('zhtfrontend', '请选择二级分类'));
        }
    }

    public function check_suitable_age($attribute){
        if($this->$attribute < $this->min_age){
            $this->addError($attribute, Yii::t('zhtfrontend', '最大年龄不能小于最小年龄'));
        }

    }

    public function afterDelete(){
        GoodsAttr::deleteAll('goods_id = :goods_id',[':goods_id'=>$this->id]);
        GoodsGroup::deleteAll('goods_id = :goods_id',[':goods_id'=>$this->id]);
        GoodsClassTime::deleteAll('goods_id = :goods_id',[':goods_id'=>$this->id]);
    }

    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
                   // ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ],
            [
                'class' => UpdateCacheBehavior::className(),
                'cacheName' => 'CateGoodsCourse',
            ],

        ]);
    }
}
